--Table of Contents--
---------------------
--A.) Database Functions
--    A1.) Create StatsDB function table
--    A2.) Create Table
--    A3.) Update Value
--    A4.) Get Value
--    A5.) Get Top 5
--B.) Stat Adding Functions
--    B1.) Create Stats function table
--    B2.) Add Time
--    B3.) Add Frags
--C.) Hooks
--    C1.) Time Timer
--    C2.) Frags Hook
--    C3.) ShowTeam Hook

require("datastream")

local function FormatID(str)
	return str:lower():gsub(":", "_")
end
	
--------------------------
--A.) Database Functions--
--------------------------
	
	---------------------------
	--A1.) Create StatsDB function table
	StatsDB = {}

	-------------------
	--A2.) Create Table
	if(sql.TableExists("rpdmstats") == false) then
	
		sql.Query("CREATE TABLE rpdmstats (steamid TEXT, lastname NUMERIC, frags NUMERIC, time TEXT)")
	
	end
	
	-------------------
	--A3.) Update Value
	function StatsDB.Update(ply, column, value)
		--Acceptable arguments are:
		--"frags"
		--"time"
		
		local steamid = FormatID(ply:SteamID())
		local name = SQLStr(string.gsub(ply:Nick(), "[^a-zA-Z0-9]", ""))
		if(name == nil or name == "") then name = "herp" end
		if(column == "frags") then
		
			if(sql.QueryValue("SELECT frags FROM rpdmstats WHERE steamid = '" .. steamid .. "'") == nil) then
			
				sql.Query("INSERT INTO rpdmstats(steamid,lastname,frags,time) VALUES(\'" .. steamid .. "\',\'" .. lastname .. "\', " .. value .. ", 0)")
				return
			
			end
			
			sql.Query("UPDATE rpdmstats SET " .. column ..  " = \'" .. value .. "\', lastname = \'" .. name  ..  "\' WHERE steamid = \'" .. steamid .. "\'")

		else if (column == "time") then
			if(sql.QueryValue("SELECT time FROM rpdmstats WHERE steamid = '" .. steamid .. "'") == nil) then
			
				sql.Query("INSERT INTO rpdmstats(steamid,lastname,frags,time) VALUES(\'" .. steamid .. "\',\'" .. lastname .. "\', 0, " .. value .. ")")
				return
			
			end
			
			sql.Query("UPDATE rpdmstats SET " .. column ..  " = \'" .. value .. "\', lastname = \'" .. name  ..  "\' WHERE steamid = \'" .. steamid .. "\'")

		else
			Error("attempted to retrieve an invalid column name from database")
		end

	end
	end

	----------------
	--A4.) Get Value
	function StatsDB.Get(ply, column)
		--Acceptable arguments are:
		--"frags"
		--"time"
		
		local steamid = FormatID(ply:SteamID())
		local name = SQLStr(string.gsub(ply:Nick(), "[^a-zA-Z0-9]", ""))
		if(name == nil) then name = "derp" end //lol ers \"
		if(column == "frags" || column == "time") then
			local result = sql.QueryValue("SELECT " .. column .. " FROM rpdmstats WHERE steamid = '" .. steamid .. "'")
			
			if(result == nil) then
				sql.Query("INSERT INTO rpdmstats(steamid,lastname,frags,time) VALUES(\'" .. steamid .. "\',\'" .. name .. "\', 0, 0)")
				result = sql.QueryValue("SELECT " .. column .. " FROM rpdmstats WHERE steamid = '" .. steamid .. "'")
			end
			
			return tonumber(result)
		
		else
		
			Error("attempted to retrieve an invalid column name from database")
		
		end
		
	end

	----------------
	--A5.) Get Top 5
	function StatsDB.GetTop5(column)
		--Acceptable arguments are:
		--"frags"
		--"time"
		--"money"
		
		if(column == "money") then
			local returningTable = sql.Query("SELECT SteamID FROM rpdmmoney ORDER BY Money DESC LIMIT 5")
			
			--This should add steamid to our output (amidoingitrite?) 
			for k,v in pairs(returningTable) do
					returningTable[k]["lastname"] = sql.QueryValue("SELECT lastname FROM rpdmstats WHERE steamid = '" .. returningTable[k]["SteamID"] .. "'")
					returningTable[k]["money"] = sql.QueryValue("SELECT money FROM rpdmmoney WHERE steamid = '" .. returningTable[k]["SteamID"] .. "'")
			end
			
			return returningTable
		end
		
		if(column == "frags" || column == "time") then
		else 
			Error("attempted to retrieve an invalid column name from database")
		end
		--Returns a table.  Use the values of the table like this:
		--1stPlaceFrags = table[1]["frags"]
		--1stPlaceSteamID = table[1]["steamid"]
		--2ndPlaceFrags = table[2]["frags"]
		--2ndPlaceSteamID = table[2]["steamid"]
		local returningTable = sql.Query("SELECT steamid, lastname, " .. column .. " FROM rpdmstats ORDER BY " .. column .. " DESC LIMIT 5")
		return returningTable
	
	end
	
-----------------------------
--B.) Stat Adding Functions--
-----------------------------

	----------------------------------
	--B1.) Create Stats function table
	Stats = {}

	---------------
	--B2.) Add Time
	function Stats.AddTime(ply, value)
		newTime = StatsDB.Get(ply, "time") + value
		StatsDB.Update(ply, "time", newTime)
		
	end
	
	----------------
	--B3.) Add Frags
	function Stats.AddFrags(ply, value)
	
		newFrags = StatsDB.Get(ply, "frags") + value
		StatsDB.Update(ply, "frags", newFrags)
		
	end
	
-------------
--C.) Hooks--
-------------
	-----------------
	--C1.) Time Timer
	timer.Create("RPDMTimeTimer", 60, 0, function()
		for k,v in pairs(player.GetAll()) do
			Stats.AddTime(v, 60)
		end
	end)
	
	-----------------
	--C2.) Frags Hook
	hook.Add("DoPlayerDeath", "StatsDeath", function(ply, attacker, dmginfo)
	
		if (attacker:IsValid() && attacker:IsPlayer()) then
	
			if(attacker == ply) then
				Stats.AddFrags(attacker, -1)
			else
				Stats.AddFrags(attacker, 1)
			end
		
		end
	
	end)
	--------------------
	--C3.) ShowHelp hook
	hook.Add("ShowHelp", "StreamStats", function(ply)
		datastream.StreamToClients(ply, "ShowTeamStatsStream", {StatsDB.Get(ply, "frags"),StatsDB.Get(ply, "time"),StatsDB.GetTop5("money"),StatsDB.GetTop5("frags"),StatsDB.GetTop5("time")})
	end)
